import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

item_transform_project_api = Blueprint('item_transform_project_api', __name__)
item_transform_project_down_api = Blueprint('item_transform_project_down_api', __name__)

USE_CMD_LOG = False


def item_transform_log(module_name, host, info):
    if USE_CMD_LOG is False:
        return
    print(f'[Item_transform] [{fomat_timestamp(int(time.time()))}] [Log] [{module_name}] host={host} - {info}', flush=True)


@item_transform_project_api.route('/item_transform_project', methods=['POST'])
def item_transform_project():
    params = json.loads(request.data)

    # host = request.host
    print(request.headers, flush=True)
    if 'X-Forwarded-For' in request.headers:
        host = request.headers['X-Forwarded-For']
    else:
        host = request.host

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        item_transform_log('project', host, f'view project list')

        query = ItemTransformProject.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "project": int(q.project),
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        item_transform_log('project', host, f'view project detail project={_project}')
        query = ItemTransformProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'detail': json.loads(query.detail)
        }
        result_data['data']['item'] = tmp

    elif _action == 'doc_id_list':
        doc_file_data = GetDocByFilename('exchange_event')
        result = []
        for k, v in doc_file_data.items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
        return json.dumps(result)

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        item_transform_log('project', host, f'update part project={_project}, part={_part}')

        if _part == 'basic':
            query = ItemTransformProject.query.filter_by(project=_project).first()
            basic = json.loads(query.basic)
            set_list = ['doc_id', 'event_ui', 'exchange_shop_id', 'al_pay_gift_id', 'exchange_reward', 'castle_lv']
            for i in set_list:
                basic[i] = _data[i]
            query.basic = json.dumps(basic)
        elif _part == 'calendar':
            query = ItemTransformProject.query.filter_by(project=_project).first()
            basic = json.loads(query.basic)
            set_list = ['calendar_doc_id', 'calendar_reward']
            for i in set_list:
                basic[i] = _data[i]
            query.basic = json.dumps(basic)
        elif _part == 'point':
            query = ItemTransformProject.query.filter_by(project=_project).first()
            basic = json.loads(query.basic)
            set_list = ['transform_gem_cost', 'transform_gem_reward', 'transform_gem_score', 'transform_gem_limit_num', 'transform_item_cost', 'transform_item_reward', 'transform_item_score', 'transform_item_limit_num']
            for i in set_list:
                basic[i] = _data['basic'][i]
            basic['rate'] = _data['table']
            query.basic = json.dumps(basic)
        elif _part == 'alliance':
            query = ItemTransformProject.query.filter_by(project=_project).first()
            detail = json.loads(query.detail)
            set_list = ['alliance_reward', 'alliance_default_icon']  # 'alliance_doc_id'
            for i in set_list:
                detail[i] = _data['basic'][i]
            detail['alliance'] = _data['table']
            query.detail = json.dumps(detail)
        elif _part == 'rank':
            query = ItemTransformProject.query.filter_by(project=_project).first()
            detail = json.loads(query.detail)
            set_list = ['rank_doc_id', 'user_score_limit']  # rank_reward
            for i in set_list:
                detail[i] = _data['basic'][i]
            detail['rank'] = _data['table']
            query.detail = json.dumps(detail)
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        item_transform_log('project', host, f'remark project={_project}')

        newRemark = params['remark']
        ItemTransformProject.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':
        item_transform_log('project', host, f'clone from={_project}')

        project_data = ItemTransformProject.query.filter_by(project=_project).first()

        new_project_data = ItemTransformProject(
            remark=project_data.remark,
            basic=project_data.basic,
            detail=project_data.detail,
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            item_transform_log('project', host, f'clone to={new_project_id}')
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        item_transform_log('project', host, f'delete project={_project}')

        project_data = ItemTransformProject.query.filter_by(project=_project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = ItemTransformProject.query.filter_by(project=_project).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'shop_name_list':
        with open(STATIC_PATH + 'shop_name.json', encoding='UTF-8') as f:
            data = json.load(f)
            _result = [{
                "label": '-1 - 不存在兑换商店',
                "value": -1
            }]
            shop_data = ShopProject.query.order_by('project').all()
            for i in data:
                _children = []
                for q in shop_data:
                    if q.shop_name == data[i]['shop_name']:
                        if q.remark is None:
                            _label = str(q.project)
                        else:
                            _label = '%s - %s' % (int(q.project), q.remark)
                        _children.append({
                            "value": int(q.project),
                            "label": _label
                        })
                _result.append({
                    "value": int(data[i]['shop_id']),
                    "label": '%s - %s' % (int(data[i]['shop_id']), data[i]['shop_name']),
                    "children": _children
                })
            return json.dumps(_result)
    elif _action == 'al_pay_gift_list':
        _result = [
            {
                'label': '-1 - 不存在联盟赠礼入口',
                'value': -1
            }
        ]
        query_data = AlPayGiftProject.query.order_by('project').all()
        for q in query_data:
            _result.append({
                'label': f'{q.project} - {q.remark}',
                'value': int(q.project)
            })
        return json.dumps(_result)

    return jsonify(result_data)


@item_transform_project_down_api.route('/item_transform_project_down/<int:is_push>', methods=['GET', 'POST'])
def item_transform_project_down(is_push):
    host = request.host

    item_transform_log('project_download', host, f'is_push={is_push}')

    item_transform_project = {}

    query = ItemTransformProject.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        detail = json.loads(q.detail)

        alliance = []
        icon_list = [detail['alliance_default_icon']]
        for i in detail['alliance']:
            icon_list.append(i['icon_id'])
            alliance.append({
                'from': 1,
                'to': i['to'],
                'reward': RewardToTMysqlNew(detail['alliance_reward']),
                # 'doc_id': detail['alliance_doc_id'],
                'doc_id': 1,
                'user_contribution_cost': i['user_contribution_cost']
            })
        user = []
        for i in detail['rank']:
            user.append({
                'from': i['from'],
                'to': i['to'],
                'reward': RewardToTMysqlNew(i['reward']),
                'doc_id': basic['doc_id']
            })

        _rank_reward = []
        if len(detail['rank']) > 0:
            _rank_reward = RewardToTMysqlNew(detail['rank'][0]['reward'])[0:2]
        
        # 20221128 优化
        """
        积分暴击概率 可选值：1,2,3,5,8
        活动日历和排行榜的doc_id配置项需要去掉
        tokenB兑换次数上限写死为-1
        """
        # 20221201 活动日历的event_ui和basic内的event_ui保持一致
        transform_info_rate = basic['rate']
        if len(transform_info_rate) == 0:
            transform_info_rate = [{'weight': 1, 'factor': 1}]
        item_transform_project[str(project)] = {
            'calendar_conf': {
                'event_type': 120,
                'event_ui': basic['event_ui'],
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['doc_id'],
                    'info': basic['doc_id']
                },
                'reward': RewardToTMysqlNew(basic['calendar_reward']),
                'show_type': 0
            },
            'basic': {
                'event_ui': basic['event_ui']
            },
            'localization_doc': {
                'title': basic['doc_id'],
                'info': basic['doc_id'],
                'content': basic['doc_id']
            },
            'calc_score': {
                'score_type_list': [
                    {"type":100003,
                     "id_list":[-1],
                     "lv_list":[-1],
                     "id_class":0,
                     "doc_id":1,
                     "num_unit":1,
                     "show":[],
                     "hide":1,
                     "class":1,
                     "num":1,
                     "score":1,
                     "task_id":0,
                     "target":0,
                     "rule_target":[0, 1],
                     "rule_type":0}
                ]
            },
            'castle_lv': basic['castle_lv'],
            'reward': {
                'goal_reward': {
                    'alliance': alliance
                },
                'rank_reward': {
                    'user': user
                }
            },
            'extern0': {
                'limit': {
                    'user_score_limit': detail['user_score_limit']
                },
                'icon_list': icon_list,
                'transform_info': {
                    'transform_gem': {
                        'cost': [
                            {
                                'a': [1, 0, basic['transform_gem_cost']]
                            }
                        ],
                        'reward': RewardToTMysqlNew(basic['transform_gem_reward']),
                        'score': basic['transform_gem_score'],
                        'limit_num': basic['transform_gem_limit_num']
                    },
                    'transform_item': {
                        'cost': RewardToTMysqlNew(basic['transform_item_cost']),
                        'reward': RewardToTMysqlNew(basic['transform_item_reward']),
                        'score': basic['transform_item_score'],
                        'limit_num': basic['transform_item_limit_num']
                    },
                    'rate': transform_info_rate
                },
                # 'rank_reward': RewardToTMysqlNew(detail['rank_reward']),
                'rank_reward': _rank_reward,
                'exchange_reward': RewardToTMysqlNew(basic['exchange_reward']),
                'exchange_shop_id': basic['exchange_shop_id'],
                'al_pay_gift_id': basic['al_pay_gift_id']
            },
            'extern1': {},
            'remark': q.remark
        }
    if is_push == 0:
        response = DownLoad('item_transform_project', item_transform_project, 0)
    if is_push == 1:
        r1 = DownLoad('item_transform_project', item_transform_project, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response
